﻿using SSHTool.Model;
using SSHTool.Util;
using System.Collections.Generic;
using System.Collections.ObjectModel;

namespace SSHTool.Service
{
    public class JsonFileService
    {
        public JsonFileService()
        {
            FilePath = Constant.DATA_DIR_NAME;
        }

        public virtual string FilePath { get; protected set; }

        public virtual string FileName { get; }

        public virtual string GetFilePath(string fileName)
        {
            return FileUtil.GetFilePath($"{FilePath}\\{fileName}");
        }

        public virtual string GetFilePath()
        {
            return FileUtil.GetFilePath($"{FilePath}\\{FileName}");
        }

        public virtual ObservableCollection<TModel> GetViewList<T, TModel>() where T : class where TModel : class
        {
            var list = GetList<T>();

            return StringUtil.CopyViewList<T, TModel>(list);
        }

        public virtual List<T> GetList<T>() where T : class
        {
            if (string.IsNullOrEmpty(FileName))
            {
                return null;
            }

            string filePath = GetFilePath();

            string json = FileUtil.ReadAllText(filePath);
            if (string.IsNullOrEmpty(json))
            {
                return null;
            }

            return StringUtil.Parse<List<T>>(json);
        }

        public virtual T GetModel<T>(int type) where T : class
        {
            if (type == 0)
            {
                if (string.IsNullOrEmpty(FileName))
                {
                    return default;
                }

                string filePath = GetFilePath();

                string json = FileUtil.ReadAllText(filePath);
                if (string.IsNullOrEmpty(json))
                {
                    return default;
                }

                return StringUtil.Parse<T>(json);
            }
            else
            {
                var list = GetList<T>();
                if (StringUtil.IsEmpty(list))
                {
                    return default;
                }
                return list[0];
            }
        }

        public virtual void Update(object model)
        {
            if (string.IsNullOrEmpty(FileName))
            {
                return;
            }

            string filePath = GetFilePath();

            FileUtil.WriteAllText(filePath, StringUtil.ToJson(model));
        }
    }
}
